package com.fyales.android.api.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author fyales
 * @since 15/11/9.
 * <p>字符操作类
 */
public class StreamUtils {

    private static final int BUFFER_SIZE = 2048;
    private static final String DEFAULT_CHARSET = "UTF-8";

    public static String readInputStream(InputStream inputStream) throws IOException {
        return readInputStream(inputStream, DEFAULT_CHARSET);
    }

    /**
     * 从输入流中读取数据
     * @throws IOException
     */
    public static String readInputStream(InputStream inputStream, String charset) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        byte[] byteArray = outputStream.toByteArray();
        inputStream.close();
        outputStream.close();
        if(charset == null){
            charset = DEFAULT_CHARSET;
        }
        return new String(byteArray, charset);
    }
}
